package com.bw.mvvm_common.network.inteceptor;

import com.bw.mvvm_common.utils.SignUtils;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Iterator;


import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * @author KK
 * @description:
 * @date :2021/10/13 15:24
 * Sign拦截器
 */
public class SignInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request oldRequest = chain.request();
        Request.Builder builder = new Request.Builder();
        builder.url(oldRequest.url());
        builder.headers(oldRequest.headers());
        RequestBody body = oldRequest.body();
        if(body == null){
            return chain.proceed(oldRequest);
        }
        Buffer buf = new Buffer();
        body.writeTo(buf);
        byte[] buff  = new byte[1024];
        String json = "";
        while (buf.read(buff )!=-1){
            json+=new String(buff);
        }
        buf.flush();
        buf.close();
        String value = "";
        String result = "";
        try {
            JSONObject job = new JSONObject(json);
            Iterator<String> it = job.keys();
            while (it.hasNext()){
                value+=job.getString(it.next());
            }
            //value=1
            String sign = SignUtils.createSign(value);
            job.put("sign",sign);
            result = job.toString();
            //{"imie":"1","sign":"516576e2bb29311613600ddaaf8fb83f"}
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),result);
        builder.post(requestBody);
        //{"imie":"1","sign":"516576e2bb29311613600ddaaf8fb83f"}
        return chain.proceed(builder.build());
    }
}
